use base64::engine::general_purpose;
use base64::Engine;
use ring::rand::{SecureRandom, SystemRandom};

//生成安全固定长度的密钥
#[test]
fn rand_gen_hmac_sha256_key() {
    println!(">>>key hex str: {}", generate_key_hex_str(32));
    println!(">>>key str: {}", generate_key_base64_str(32));

    let key = generate_key_hex_str(32);
    println!(">>>size: {}", key.len());
}

///随机生成length位key，hex字符串形式返回
fn generate_key_hex_str(length: usize) -> String {
    let rng = SystemRandom::new(); // 与系统有关
    let mut bytes = vec![0u8; length];
    rng.fill(&mut bytes)
        .expect("failed to generate random bytes");

    //方式一
    bytes.into_iter().map(|b| format!("{:02x}", b)).collect()

    //方式二,小写
    // hex::encode(bytes)

    //大写
    // hex::encode_upper(bytes)
}

/// 生成随机length位key，base64字符串形式返回
fn generate_key_base64_str(length: usize) -> String {
    let rng = SystemRandom::new();
    let mut bytes = vec![0u8; length];
    rng.fill(&mut bytes)
        .expect("failed to generate random bytes");

    general_purpose::STANDARD_NO_PAD.encode(bytes)
}

#[test]
fn test1() {
    println!("{}", generate_key_base64_str(32));
}
